{extend name="public:base" /}{block name="css"}
<link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css"/>
<link href="__ADMIN__/css/style.css" rel="stylesheet">

{/block}{block name="content"}

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox ">
                <div class="ibox-content">
                    <form method="post">
                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">规则名称</label>
                                <div class="col-sm-3">
                                    <input type="text" class="form-control" name="name" value="{$info.name}" placeholder="请输入规则名称">
                                </div>
                            </div>
                        </div>

                        <div class="hr-line-solid"></div>

                        <div class="box-item">
                            <div class="form-group row">
                                <h3 class="col-sm-2">绑定老师与课程</h3>
                            </div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row layui-form">
                                <label class="col-sm-1 col-form-label">老师-课程</label>
                                <div class="col-sm-2">
                                    <select name="teacher_id" lay-filter="teacherSelect" lay-verify="required" lay-search="">
                                        <option value="">请选择老师</option>
                                    </select>
                                </div>
                                <div class="col-sm-2">
                                    <select name="course_id" lay-filter="courseSelect" lay-verify="required">
                                        <option value="">请选择课程</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="hr-line-solid"></div>

                        <div class="box-item">
                            <div class="form-group row">
                                <h3 class="col-sm-1">结算周期基准</h3>
                            </div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row layui-form">
                                <h4 class="col-sm-2 col-form-label">周期计算依据：按课程开始日期</h4>
                            </div>
                        </div>
                        <div class="hr-line-solid"></div>

                        <div class="box-item">
                            <div class="form-group row">
                                <h3 class="col-sm-2">分期拨付比例设置</h3>
                            </div>
                        </div>

                        <style>
                            .rule-form {
                                width: 30%;
                                display: flex;
                                flex-direction: column;
                                border: 1px solid #ccc;
                                border-radius: 10px;
                                padding: 20px;
                                margin-bottom: 20px;
                            }

                            .add-box {
                                width: 100%;
                                display: flex;
                                justify-content: flex-end;
                            }

                            .rule-row {
                                width: 100%;
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                margin-top: 14px;
                            }

                            .rule-row .row-left {
                                display: flex;
                                align-items: center;
                            }

                            .rule-row .row-right {
                                display: flex;
                                align-items: center;
                                justify-content: flex-end;
                            }

                            .delete-btn {
                                margin-left: 20px;
                                color: #fff;
                            }

                            .all {
                                margin-top: 20px;
                            }
                        </style>
                        <div class="rule-form">
                            <div class="add-box">
                                <div class="btn btn-primary btn-lg add-btn">新增分期拨付比例</div>
                            </div>
                            <div class="rule-row">
                                <div class="row-left">
                                    <span>1：【课程开始日】第</span>
                                    <input type="number" class="form-control col-sm-3" value="">
                                    <span>个自然日</span>
                                </div>
                                <div class="row-right">
                                    <input type="text" class="form-control col-sm-3" value="">%
                                    <div class="btn layui-btn-danger btn-lg delete-btn">删除</div>
                                </div>
                            </div>
                            <div class="rule-row">
                                <div class="row-left">
                                    <span>2：【课程开始日】第</span>
                                    <input type="text" class="form-control col-sm-3" value="">
                                    <span>个自然日</span>
                                </div>
                                <div class="row-right">
                                    <input type="number" class="form-control col-sm-3" value="">%
                                    <div class="btn layui-btn-danger btn-lg delete-btn">删除</div>
                                </div>
                            </div>

                            <h4 class="all">总计：100%</h4>
                        </div>

                        <input type="hidden" name="id" value="{:input('id')}">

                        <div class="form-group row">
                            <div class="col-sm-4 col-sm-offset-2">
                                <button type="button" class="btn btn-w-m btn-default back-page">返回</button>
                                <button type="button" class="btn btn-w-m btn-primary" onclick="save()">保存</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>{/block}


{block name='js'}
<script src="__STATIC__/layui/layui.js"></script>
<script>
    $(function () {
        // 老师-课程数据
        const teacherCourseData = [
            {
                "teacher_id": "1",
                "teacher": "李华",
                "courses": [
                    {"course_id": "101", "course": "高等数学"},
                    {"course_id": "102", "course": "线性代数"},
                    {"course_id": "103", "course": "概率论与数理统计"}
                ]
            },
            {
                "teacher_id": "2",
                "teacher": "王芳",
                "courses": [
                    {"course_id": "201", "course": "大学英语"},
                    {"course_id": "202", "course": "英语写作"}
                ]
            }
        ];

        // 假设这是编辑时需要回显的数据（实际应从后端获取）
        var teacherCourse = {$teacherCourse} ? {$teacherCourse} : {};
        // 初始化layui
        layui.use(['form'], function () {
            const form = layui.form;

            // 渲染老师下拉框
            renderTeacherSelect(form);

            // 监听老师选择变化
            form.on('select(teacherSelect)', function (data) {
                const selectedTeacherId = data.value;
                renderCourseSelect(form, selectedTeacherId);
            });

            // 如果有编辑数据，进行回显
            if (teacherCourse.teacher_id) {
                // 设置老师选中
                $('select[name="teacher_id"]').val(teacherCourse.teacher_id);
                form.render('select');

                // 渲染该老师的课程
                renderCourseSelect(form, teacherCourse.teacher_id, teacherCourse.course_id);
            }
        });

        // 渲染老师下拉框
        function renderTeacherSelect(form) {
            const teacherSelect = $('select[name="teacher_id"]');

            // 清空并添加默认选项
            teacherSelect.empty().append('<option value="">请选择老师</option>');

            // 添加老师选项
            teacherCourseData.forEach(function (item) {
                teacherSelect.append('<option value="' + item.teacher_id + '">' + item.teacher + '</option>');
            });

            // 重新渲染
            form.render('select');
        }

        // 渲染课程下拉框
        function renderCourseSelect(form, teacherId, selectedCourseId = '') {
            const courseSelect = $('select[name="course_id"]');

            // 清空并添加默认选项
            courseSelect.empty().append('<option value="">请选择课程</option>');

            // 如果选择了老师，添加对应课程
            if (teacherId) {
                const teacher = teacherCourseData.find(item => item.teacher_id == teacherId);
                if (teacher && teacher.courses) {
                    teacher.courses.forEach(function (course) {
                        courseSelect.append('<option value="' + course.course_id + '">' + course.course + '</option>');
                    });
                }
            }

            // 如果有选中的课程，进行回显
            if (selectedCourseId) {
                courseSelect.val(selectedCourseId);
            }

            // 重新渲染
            form.render('select');
        }

        // 初始化数据示例
        const config = {$config} ? {$config} : [];

        // 初始化渲染数据
        initRuleRows(config);

        // 点击新增按钮添加新的规则行
        $('.add-btn').on('click', function () {
            addRuleRow();
            updateTotalRate();
        });

        // 点击删除按钮移除规则行
        $(document).on('click', '.delete-btn', function () {
            $(this).closest('.rule-row').remove();
            updateRuleNumbers();
            updateTotalRate();
        });

        // 监听输入变化，更新总计
        $(document).on('input', '.rule-row input', function () {
            updateTotalRate();
        });

        // 初始化规则行
        function initRuleRows(data) {
            // 先清空现有的规则行（保留结构）
            $('.rule-row').remove();

            // 添加初始数据行
            data.forEach(function (item, index) {
                addRuleRow(item.day, item.rate);
            });

            updateTotalRate();
        }

        // 添加规则行
        function addRuleRow(day = '', rate = '') {
            const ruleCount = $('.rule-row').length + 1;

            const newRow = $(
              '<div class="rule-row">' +
              '    <div class="row-left">' +
              '        <span>' + ruleCount + '：【课程开始日】第</span>' +
              '        <input type="text" class="form-control col-sm-3 day-input" value="' + day + '">' +
              '        <span>个自然日</span>' +
              '    </div>' +
              '    <div class="row-right">' +
              '        <input type="text" class="form-control col-sm-3 rate-input" value="' + rate + '">%' +
              '        <div class="btn layui-btn-danger btn-lg delete-btn">删除</div>' +
              '    </div>' +
              '</div>'
            );

            // 插入到总计前面
            $('.all').before(newRow);
        }

        // 更新规则序号
        function updateRuleNumbers() {
            $('.rule-row').each(function (index) {
                $(this).find('.row-left span:first').text((index + 1) + '：【课程开始日】第');
            });
        }

        // 更新总计百分比
        function updateTotalRate() {
            let totalRate = 0;
            $('.rate-input').each(function () {
                const value = parseFloat($(this).val()) || 0;
                totalRate += value;
            });
            $('.all').text('总计：' + totalRate + '%');
        }

        // 保存设置方法
        window.save = function () {
            // 收集老师-课程数据
            const id = $('input[name="id"]').val();
            const name = $('input[name="name"]').val();
            const teacherId = $('select[name="teacher_id"]').val();
            const courseId = $('select[name="course_id"]').val();

            // 收集分期拨付比例数据
            const ruleList = [];
            let isValid = true;
            let totalRate = 0;

            $('.rule-row').each(function (index) {
                const day = $(this).find('.day-input').val();
                const rate = $(this).find('.rate-input').val();

                // 验证输入
                if (!day || !rate) {
                    isValid = false;
                    layer.msg('请填写完整的分期拨付比例信息');
                    return false; // 中断each循环
                }

                const dayNum = parseInt(day);
                const rateNum = parseFloat(rate);

                if (isNaN(dayNum) || dayNum <= 0) {
                    isValid = false;
                    layer.msg('天数必须是大于0的数字');
                    return false;
                }

                if (isNaN(rateNum) || rateNum < 0) {
                    isValid = false;
                    layer.msg('百分比必须是非负数字');
                    return false;
                }

                ruleList.push({day: dayNum, rate: rateNum});
                totalRate += rateNum;
            });

            // 验证老师和课程选择
            if (!teacherId) {
                isValid = false;
                layer.msg('请选择老师');
            } else if (!courseId) {
                isValid = false;
                layer.msg('请选择课程');
            }

            // 验证百分比总和是否为100%
            if (Math.abs(totalRate - 100) > 0.01) { // 允许小数点误差
                isValid = false;
                layer.msg('分期拨付比例总和必须为100%');
            }

            // 如果验证通过，发送请求
            if (isValid) {
                // 根据选中的ID获取老师和课程名称
                let teacherName = '';
                let courseName = '';

                // 查找选中的老师
                const selectedTeacher = teacherCourseData.find(item => item.teacher_id === teacherId);
                if (selectedTeacher) {
                    teacherName = selectedTeacher.teacher;

                    // 查找选中的课程
                    const selectedCourse = selectedTeacher.courses.find(course => course.course_id === courseId);
                    if (selectedCourse) {
                        courseName = selectedCourse.course;
                    }
                }

                // 构建请求数据
                const requestData = {
                    id: id,
                    name: name,
                    teacher_id: teacherId,
                    teacher: teacherName,
                    course_id: courseId,
                    course: courseName,
                    rules: ruleList
                };

                // 发送AJAX请求
                $.ajax({
                    url: '/admin/manage/doSettlementRule',
                    type: 'POST',
                    data: JSON.stringify(requestData),
                    contentType: 'application/json',
                    dataType: 'json',
                    beforeSend: function () {
                        // 可以在这里显示加载中状态
                        layer.load();
                    },
                    success: function (response) {
                        layer.closeAll('loading');

                        // 根据后端返回的状态处理
                        if (response.result === 1) {
                            layer.msg(response.msg, {icon: 6});
                            // 可以选择跳转到其他页面
                            setTimeout(function () {
                                window.location.href = response.url;
                            }, 1000);
                        } else {
                            layer.msg(response.msg || '保存失败', {icon: 5});
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.closeAll('loading');
                        layer.msg('网络错误，请稍后重试', {icon: 5});
                        console.error('保存失败:', error);
                    }
                });
            }
        }

        // 返回按钮事件
        $('.back-page').on('click', function () {
            // 可以根据需求修改返回逻辑
            window.history.back();
        });
    });
</script>{/block}